﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ProtocoloNameSpace;
using HTSwitchServerNamespace.ar.com.horsetrack;
using Newtonsoft.Json;
using HTSwitchServerNamespace.DataMocks;

namespace HTSwitchServerNamespace.Protocols
{
    public class Protocol_AndroidForGooglePlayGps : IProtocol
    {
        #region MetodosDatosDispositivoAndroid Google PLay
        public bool ObteneryEnviarDatosDelDispositivo(string strMensajeDelDispositivo)
        {
            ///DECLARACION DE VARIABLES
            HTSwitchServerNamespace.ar.com.horsetrack.DatosGPS objDatosGPS = new HTSwitchServerNamespace.ar.com.horsetrack.DatosGPS();
            ControlHorseData objContext = new ControlHorseData();
            DataMockAndroidForGooglePlay objGPSAndroidDataGPLAY = new DataMockAndroidForGooglePlay();
            ar.com.controlyseguimiento.www.ControlYSeguimiento objContextControl = new ar.com.controlyseguimiento.www.ControlYSeguimiento();

            ///INICIO EL CUERPO DEL PROGRAMA
            try
            {
                ///EJEMPLO DE ENVIO {"Id":"And4GPlay","Lat":"-34.55554815999999","Lng":"-58.46642887","Alt":"0.0","Spe":"0.0","IMEI":"358306041574731","Mail":"j","User":"lala","Pass":"pepe"}

                objGPSAndroidDataGPLAY = JsonConvert.DeserializeObject<DataMockAndroidForGooglePlay>(strMensajeDelDispositivo);
            }
            catch (Exception ex)
            {
                //CLogger.Append("ERROR Obteneiendo JSON: " + ex.ToString(), CLogger.ERROR);
                throw ex;
            }
            
         
            ////////////////////////////////////////////////////////////////////PLATAFORMA NUEVA ///////////////////////////////////////7//            
            try
            {
                if ((objGPSAndroidDataGPLAY != null) && (objGPSAndroidDataGPLAY.Mail != null) && (objGPSAndroidDataGPLAY.Mail != "Not defined") && (objGPSAndroidDataGPLAY.Lat != null) && (objGPSAndroidDataGPLAY.Lng != null))
                {

                    CLogger.Append("*************************NEW PLATFORM********************", CLogger.INFO);

                    #region Validar Nueva plataforma

                    if (objContextControl.ValidateImei(objGPSAndroidDataGPLAY.IMEI) == true)
                    {
                        //CLogger.Append("Imei encontrado:" + objGPSAndroidData.IMEI, CLogger.INFO);

                        if (objContextControl.IsFirstTimeActivation(objGPSAndroidDataGPLAY.Mail) == true)  //AVERIGUA SI ES PRIMERA VES PARA ACTIVAR
                        {
                            if (objContextControl.FirstTimeActivation(objGPSAndroidDataGPLAY.IMEI, objGPSAndroidDataGPLAY.Mail) == true)  //ACTIVA POR PRIMERA VEZ
                            {
                                CLogger.Append("**NEW PLATFORM** GPLAY Se activa por primera vez el usuario: " + objGPSAndroidDataGPLAY.Mail + " con IMEI:" + objGPSAndroidDataGPLAY.IMEI, CLogger.INFO);
                                //CLogger.Append("NOKIA Actualizando usuario con IMEI:" + objGPSNokiaData.IMEI, CLogger.INFO);
                                objContextControl.UpdateCoordinates(objGPSAndroidDataGPLAY.IMEI,
                                                                    objGPSAndroidDataGPLAY.Mail,
                                                                    objGPSAndroidDataGPLAY.Lat,
                                                                    objGPSAndroidDataGPLAY.Lng,
                                                                    "0",
                                                                    objGPSAndroidDataGPLAY.Alt,
                                                                    objGPSAndroidDataGPLAY.Spe,
                                                                    "0"//objGPSAndroidDataGPLAY.Batt
                                                                    );
                                CLogger.Append("**NEW PLATFORM** GPLAY Actualizo correctamente - Mail: " + objGPSAndroidDataGPLAY.Mail + " - IMEI:" + objGPSAndroidDataGPLAY.IMEI, CLogger.INFO);
                            }

                        }
                        else
                        {              //IMEI CORRECTO

                            objContextControl.UpdateCoordinates(objGPSAndroidDataGPLAY.IMEI,
                                                                objGPSAndroidDataGPLAY.Mail,
                                                                objGPSAndroidDataGPLAY.Lat,
                                                                objGPSAndroidDataGPLAY.Lng,
                                                                "0",
                                                                objGPSAndroidDataGPLAY.Alt,
                                                                objGPSAndroidDataGPLAY.Spe,
                                                                "0"//objGPSAndroidDataGPLAY.Batt
                                                                );
                            CLogger.Append("**NEW PLATFORM** GPLAY Actualizo correctamente - Mail: " + objGPSAndroidDataGPLAY.Mail + " - IMEI:" + objGPSAndroidDataGPLAY.IMEI, CLogger.INFO);

                        }
                    }
                    else
                    {
                        CLogger.Append("**NEW PLATFORM** GPLAY IMEI INVALIDO - IMEI:" + objGPSAndroidDataGPLAY.IMEI, CLogger.INFO);

                    }
                    #endregion
                }
                else
                {

                    CLogger.Append("**NEW PLATFORM** GPLAY DATOS ENVIADOS INVALIDOS O VACIOS " + objGPSAndroidDataGPLAY.Mail, CLogger.INFO);
                    return false;
                }
            }
            catch (Exception ex)
            {
                //throw new Exception("ERROR EN VALIDACION O CREACION DE NUEVO USUARIO" + objGPSAndroidData.Mail);
                CLogger.Append("**NEW PLATFORM** ANDROID GPLAY ERROR EN NUEVO VALIDATE: " + ex.Message, CLogger.ERROR);
            }


            CLogger.Append("*************************OLD PLATFORM********************", CLogger.INFO);
            ////////////////////////////////////////////////////////////////////PLATAFORMA VIEJA ///////////////////////////////////////7//            
            ar.com.horsetrack.HorsetrackWebService webServiceHandler = new ar.com.horsetrack.HorsetrackWebService();

            try
            {
                if ((objGPSAndroidDataGPLAY != null) && (objGPSAndroidDataGPLAY.Mail != null) && (objGPSAndroidDataGPLAY.Mail != "Not defined") && (objGPSAndroidDataGPLAY.Lat != null) && (objGPSAndroidDataGPLAY.Lng != null))
                {
                    
                    //CLogger.Append("INFO MAIL ENVIO: "+objGPSAndroidData.Mail, CLogger.INFO);    //FD
                    if (webServiceHandler.ExisteImei(objGPSAndroidDataGPLAY.IMEI) == true)
                    {
                        //CLogger.Append("EXISTE IMEI - DEBUG ", CLogger.INFO);
                        objDatosGPS = objContext.obtenerDatosGPSAndroidGooglePlay(objGPSAndroidDataGPLAY);                        
                    }
                    else
                    {
                        // CLogger.Append("NO EXISTE IMEI - DEBUG ", CLogger.INFO);
                        string[] strClientHost = new string[5];
                        string strMensaje;
                        if (objContext.boAgregarPosibleUsuarioNuevo(objGPSAndroidDataGPLAY.User, objGPSAndroidDataGPLAY.Pass, objGPSAndroidDataGPLAY.Mail, objGPSAndroidDataGPLAY.IMEI) == true)
                        {
                            CLogger.Append("**OLD PLATFORM** Nuevo Usuario en el Sistema Gplay: User: " + objGPSAndroidDataGPLAY.User + " - Mail: " + objGPSAndroidDataGPLAY.Mail, CLogger.INFO);
                            objDatosGPS = objContext.obtenerDatosGPSAndroidGooglePlay(objGPSAndroidDataGPLAY);
                            strClientHost[0] = "mail.horsetrack.com.ar";
                            strClientHost[1] = "25";
                            strClientHost[2] = "activaruser@horsetrack.com.ar";
                            strMensaje = "Nuevo Usuario Google Play en el sistema. Usuario: " + objGPSAndroidDataGPLAY.User + " - IMEI: " + objGPSAndroidDataGPLAY.IMEI + " - MAIL: " + objGPSAndroidDataGPLAY.Mail;
                            HTMailSenderNamespace.SimpleAsynchronousExample.MailActivarUsuario(strClientHost, "Nuevo ususario GPlay", "activaruser@horsetrack.com.ar", strMensaje);
                        }
                    }
                }
                else
                {
                    CLogger.Append("**OLD PLATFORM** GPLAY DATOS INVALIDOS O VACIOS " + objGPSAndroidDataGPLAY.Mail, CLogger.INFO);
                    return false;
                    //throw new Exception("**OLD PLATFORM** Datos Android Play Vacios");
                }
            }
            catch (Exception ex)
            {
                CLogger.Append("**OLD PLATFORM** ERROR Obteniendo DatosGPS Android Gplay: " + ex.Message, CLogger.ERROR);
                throw ex;
            }


            if (webServiceHandler.actualizarDatosGPSenDB(objDatosGPS) == true)  //ACTUALIZACION DATOS EN PLATAFORMA HORSETRACK
            {
                CLogger.Append("**OLD PLATFORM** DATOS ACTUALIZADOS CORRECTAMENTE OK", CLogger.ERROR);
            }
            else
            {
                throw new Exception("**OLD PLATFORM** ANDROID GPLAY NO SE PUDO ACTUALIZAR LA DB DE HORSETRACK");
            }
            
            return true;
        }
        #endregion

        #region PARSE GOOGLE PLAY
        public ar.com.horsetrack.DatosGPS Parse(DataMockMgr mockObject)
        {
            throw new NotImplementedException();
        }
        #endregion
    }
}
